package com.leyou.auth.service;

import com.leyou.auth.config.JwtProperties;
import com.leyou.common.auth.JwtUtils;
import com.leyou.common.auth.Payload;
import com.leyou.common.auth.UserInfo;
import com.leyou.common.constants.UserTokenConstants;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exception.LyException;
import com.leyou.common.utils.CookieUtils;
import com.leyou.user.client.UserClient;
import com.leyou.user.dto.UserDTO;
import io.jsonwebtoken.ExpiredJwtException;
import org.apache.commons.lang3.BooleanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

/**
 * @author 虎哥
 */
@Service
public class AuthService {

    @Autowired
    private UserClient userClient;

    @Autowired
    private JwtProperties prop;

    public void login(String username, String password, HttpServletResponse response) {
        // 	1.去ly-user根据用户名和密码查询用户
        UserDTO user;
        try {
            user = userClient.queryUserByUsernameAndPassword(username, password);
        } catch (Exception e) {
            // 查询失败，登录失败
            throw new LyException(ExceptionEnum.INVALID_USERNAME_PASSWORD);
        }
        //	2.判断查询结果
        if (user == null) {
            // 查询失败，登录失败
            throw new LyException(ExceptionEnum.INVALID_USERNAME_PASSWORD);
        }
        //	3.如果成功，利用私钥，生成JWT
        UserInfo userInfo = new UserInfo(user.getId(), user.getUsername(), "guest");
        String token = JwtUtils.generateTokenExpireInMinutes(userInfo, prop.getPrivateKey(), UserTokenConstants.EXPIRE_MINUTES);
        //	4.把JWT写入用户cookie
        writeTokenToCookie(response, token);
    }

    public UserInfo verify(HttpServletRequest request, HttpServletResponse response) {
        // 1.接收请求，获取cookie中的token
        String token = CookieUtils.getCookieValue(request, UserTokenConstants.COOKIE_NAME);
        // 2.利用公钥验证并解析token
        Payload<UserInfo> payload = null;
        try {
            payload = JwtUtils.getInfoFromToken(token, prop.getPublicKey(), UserInfo.class);
        } catch (Exception e) {
            throw new LyException(ExceptionEnum.UNAUTHORIZED, e);
        }
        // 3.验证redis黑名单
        Boolean isExists = redisTemplate.hasKey(payload.getId());
        if(BooleanUtils.isTrue(isExists)){
            // 存在redis黑名单，说明token是无效token
            throw new LyException(ExceptionEnum.UNAUTHORIZED);
        }
        // 4.是否需要刷新token
        // 4.1.获取剩余有效期
        long remainTime = payload.getExpiration().getTime() - System.currentTimeMillis();
        // 4.2.判断有效期时长是否小于某个值
        if (remainTime < UserTokenConstants.TOKEN_REFRESH_MILLIS) {
            // 4.3.重新生成token
            token = JwtUtils.generateTokenExpireInMinutes(payload.getUserInfo(), prop.getPrivateKey(), UserTokenConstants.EXPIRE_MINUTES);
            // 4.4.覆盖以前的token
            writeTokenToCookie(response, token);
        }
        // 5.获取用户并返回
        return payload.getUserInfo();
    }

    private void writeTokenToCookie(HttpServletResponse response, String token) {
        CookieUtils.newCookieBuilder().response(response)
                .name(UserTokenConstants.COOKIE_NAME)
                .value(token)
                .domain(UserTokenConstants.DOMAIN)
                .httpOnly(true)
                .build();
    }

    @Autowired
    private StringRedisTemplate redisTemplate;

    public void logout(HttpServletRequest request, HttpServletResponse response) {
        // 1.获取token
        String token = CookieUtils.getCookieValue(request, UserTokenConstants.COOKIE_NAME);
        // 2.解析出token的剩余有效期
        Payload<Object> payload = JwtUtils.getInfoFromToken(token, prop.getPublicKey());
        long remainTime = payload.getExpiration().getTime() - System.currentTimeMillis();
        // 3.把token及token的id存储到redis，设置有效期为token有效期
        redisTemplate.opsForValue().set(payload.getId(), "", remainTime, TimeUnit.MILLISECONDS);
        // 4.删除cookie（重写一个一样的cookie，有效期为0）
        CookieUtils.deleteCookie(UserTokenConstants.COOKIE_NAME, UserTokenConstants.DOMAIN, response);
    }
}
